package com.i360day.common.security;

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;


public abstract class AbstractGenerator {
	
	/**
	 * 
	 *<P>@method: createKey</p>
	 *	
	 *<p>Title: 根据用户生成相应的参数 <／p>
	 *
	 *<p>@author z.liju<／p>
	 *
	 *<p>2018年11月23日 下午12:36:23<／p>
	 *
	 *<p>return parameter：KeyModel  <／p>
	 *
	 *@param userName
	 *@param password
	 *@return
	 *@throws Exception
	 */
	public static SecurityModel createSecurityKey(String userName, String password) throws Exception{
		SecurityModel keyModel = new SecurityModel();
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(AbstractKey.KEY_ALGORITHM);
		keyPairGen.initialize(1024, new SecureRandom());
		KeyPair keyPair = keyPairGen.generateKeyPair();
		Key publicKey = keyPair.getPublic();
		Key privateKey =  keyPair.getPrivate();
		keyModel.setPublicKey(AbstractKey.encryptBASE64(publicKey.getEncoded()));
		keyModel.setPrivateKey(AbstractKey.encryptBASE64(privateKey.getEncoded()));
		keyModel.setAppKey(Md5Utils.hash(userName));
		keyModel.setAppSecurity(Md5Utils.hash(password));
		return keyModel;
	}

	/**
	 *
	 *<P>@method: createKey</p>
	 *
	 *<p>Title: 根据用户生成相应的参数 <／p>
	 *
	 *<p>@author z.liju<／p>
	 *
	 *<p>2018年11月23日 下午12:36:23<／p>
	 *
	 *<p>return parameter：KeyModel  <／p>
	 *
	 *@return
	 *@throws Exception
	 */
	public static SecurityModel createSecurityKey() throws Exception{
		SecurityModel keyModel = new SecurityModel();
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(AbstractKey.KEY_ALGORITHM);
		keyPairGen.initialize(1024, new SecureRandom());
		KeyPair keyPair = keyPairGen.generateKeyPair();
		Key publicKey = keyPair.getPublic();
		Key privateKey =  keyPair.getPrivate();
		keyModel.setPublicKey(AbstractKey.encryptBASE64(publicKey.getEncoded()));
		keyModel.setPrivateKey(AbstractKey.encryptBASE64(privateKey.getEncoded()));
		keyModel.setAppKey("hd." + Md5Utils.hash(keyModel.getPublicKey()));
		keyModel.setAppSecurity(Base64Util.encode(Md5Utils.hash(keyModel.getPrivateKey()).getBytes()));
		return keyModel;
	}
}
